import axios from 'axios'
import {RESPONSE_CODE_LOGIN_INVALID, RESPONSE_CODE_SUCCESS} from "@/constant/response"
import {Message} from "view-ui-plus"
import router from "@/router";
import storage from "@/config/storage";

axios.defaults.baseURL = import.meta.env.VITE_API_BASE_URL;
axios.defaults.timeout = 5000
axios.defaults.withCredentials = true

declare module 'axios' {
    interface AxiosRequestConfig {
        // 不展示错误信息,默认展示
        hideErrorMsg?: boolean;
        // 是否响应原始内容,不进行任何处理,默认处理
        responseRaw?: boolean;
    }

    interface AxiosHeaders {
        access_token?: string
    }
}

axios.interceptors.request.use((config) => {
    let accessToken = storage.getItem("accessToken");
    if (accessToken) {
        // @ts-ignore
        config.headers['Access-Token'] = accessToken as string;
    }
    return config;
})

/**
 * 响应拦截器
 */
axios.interceptors.response.use(res => {
    let {data, config} = res;
    if (config.responseRaw) {
        return res
    }
    if (config.responseType === 'blob') {
        downloadFile(res)
        return res
    }
    if (data && data.code == RESPONSE_CODE_SUCCESS) {
        return data
    }
    if (!config.hideErrorMsg) {
        Message.error(data.msg);
    }
    return data
}, err => {
    let {code, config, response} = err;
    if (code == 'ERR_BAD_RESPONSE') {
        err.message = response.data.msg
        if (!err.message || err.message == '') {
            err.message = response.statusText
        }
    }
    if (!config.hideErrorMsg) {
        if (code == 'ERR_NETWORK') {
            Message.error('网络异常,请检查网络');
        } else if (code == 'ERR_BAD_REQUEST' && response.data.code != RESPONSE_CODE_SUCCESS) {
            let {code, mst} = response.data
            if (code == RESPONSE_CODE_LOGIN_INVALID) {
                Message.error('登陆失效');
                storage.clear()
                router.push({path: '/login'})
            } else {
                Message.error(response.data.msg);
            }
        } else {
            Message.error(err.message);
        }
    }
    return Promise.reject(err)
})

function downloadFile(res: any) {
    let {data, headers} = res;
    let fileName = decodeURIComponent(headers["content-disposition"].split("=")[1])
    const blobUrl = window.URL.createObjectURL(data);
    const a = document.createElement('a');
    a.href = blobUrl;
    a.download = fileName;
    document.body.appendChild(a);
    a.click();
    window.URL.revokeObjectURL(blobUrl);
    document.body.removeChild(a);
}
